@{
    ViewData["Title"] = "智能客服";
    var sessionId = ViewBag.SessionId;
    var userId = ViewBag.UserId;
}

<div class="container-fluid">
    <div class="row">
        <!-- 聊天主界面 -->
        <div class="col-lg-8">
            <div class="card border-0 shadow h-100">
                <div class="card-header bg-primary text-white">
                                            <div class="d-flex align-items-center">
                            <div class="bg-white bg-opacity-25 rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                <i class="fas fa-robot text-white"></i>
                            </div>
                            <div>
                                <h5 class="mb-0 fw-bold">智能客服助手</h5>
                                <small class="opacity-75">基于AI技术的智能客服系统</small>
                            </div>
                            <div class="ms-auto d-flex align-items-center gap-2">
                                <button class="btn btn-sm btn-outline-light me-2" id="handoffBtn">
                                    <i class="fas fa-user-headset me-1"></i>转人工
                                </button>
                                <span class="badge bg-success">在线</span>
                            </div>
                        </div>
                </div>
                
                <div class="card-body p-0 d-flex flex-column" style="height: 600px;">
                    <!-- 聊天消息区域 -->
                    <div id="chatMessages" class="flex-grow-1 p-3 overflow-auto" style="max-height: 500px;">
                        <!-- 欢迎消息 -->
                        <div class="d-flex mb-3">
                            <div class="flex-shrink-0">
                                <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                    <i class="fas fa-robot text-white"></i>
                                </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <div class="bg-light rounded p-3">
                                    <p class="mb-0">您好！我是您的智能客服助手，很高兴为您服务。我可以帮助您：</p>
                                    <ul class="mb-0 mt-2">
                                        <li>查询生产信息和设备状态</li>
                                        <li>创建和管理工单</li>
                                        <li>调整生产计划</li>
                                        <li>解答技术问题</li>
                                        <li>提供操作指导</li>
                                    </ul>
                                    <p class="mb-0 mt-2">请告诉我您需要什么帮助？</p>
                                </div>
                                <small class="text-muted">@DateTime.Now.ToString("HH:mm")</small>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 消息输入区域 -->
                    <div class="border-top p-3">
                        <div class="input-group">
                            <textarea id="messageInput" class="form-control border-0" rows="1"
                                      placeholder="请输入您的问题...（Enter 发送，Shift+Enter 换行）"
                                      style="box-shadow: none; resize: none;"></textarea>
                            <button class="btn btn-primary" type="button" id="sendButton">
                                <i class="fas fa-paper-plane me-1"></i>发送
                            </button>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-2">
                            <small class="text-muted">
                                会话ID: <span class="text-primary">@sessionId</span> | 
                                用户ID: <span class="text-primary">@userId</span>
                            </small>
                            <div>
                                <button class="btn btn-sm btn-outline-secondary me-2" id="clearChat">
                                    <i class="fas fa-trash me-1"></i>清空对话
                                </button>
                                <button class="btn btn-sm btn-outline-info" id="loadHistory">
                                    <i class="fas fa-history me-1"></i>加载历史
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-lg-4">
            <!-- 建议操作 -->
            <div class="card border-0 shadow mb-4">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="fas fa-lightbulb text-warning me-2"></i>建议操作
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div id="suggestedActions" class="list-group list-group-flush">
                        <div class="list-group-item border-0 d-flex align-items-start">
                            <div class="me-2 text-warning"><i class="fas fa-lightbulb"></i></div>
                            <div>
                                <div class="fw-bold">开始对话后展示建议操作</div>
                                <small class="text-muted">也可以直接点击右下角的“快捷问题”或输入框下方的提示</small>
                            </div>
                        </div>
                        <div class="list-group-item">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-headset text-primary me-2"></i>
                                <div>
                                    <div class="fw-bold">联系人工客服</div>
                                    <small class="text-muted">复杂问题可转人工处理</small>
                                </div>
                                <button class="btn btn-sm btn-outline-primary ms-auto" id="suggestHandoff">转人工</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 快速问题 -->
            <div class="card border-0 shadow mb-4">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="fas fa-question-circle text-info me-2"></i>快速问题
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        <button class="list-group-item list-group-item-action border-0 quick-question" data-question="查询设备A的当前产量">
                            <i class="fas fa-chart-line text-primary me-2"></i>查询设备产量
                        </button>
                        <button class="list-group-item list-group-item-action border-0 quick-question" data-question="如何创建新的工单">
                            <i class="fas fa-plus text-success me-2"></i>创建工单
                        </button>
                        <button class="list-group-item list-group-item-action border-0 quick-question" data-question="查看生产计划">
                            <i class="fas fa-calendar text-warning me-2"></i>生产计划
                        </button>
                        <button class="list-group-item list-group-item-action border-0 quick-question" data-question="设备维护手册">
                            <i class="fas fa-tools text-info me-2"></i>维护手册
                        </button>
                    </div>
                </div>
            </div>

            <!-- 系统状态 -->
            <div class="card border-0 shadow">
                <div class="card-header bg-light">
                    <h6 class="mb-0">
                        <i class="fas fa-server text-success me-2"></i>系统状态
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>AI服务</span>
                        <span class="badge bg-success">正常</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>MES连接</span>
                        <span class="badge bg-success">正常</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>知识库</span>
                        <span class="badge bg-success">正常</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <span>响应时间</span>
                        <span class="text-muted">&lt; 2秒</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 评价模态框 -->
<div class="modal fade" id="ratingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-star text-warning me-2"></i>评价回复质量
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">请为这个回复打分：</label>
                    <div class="rating-stars text-center">
                        <i class="fas fa-star fa-2x text-muted me-2" data-rating="1"></i>
                        <i class="fas fa-star fa-2x text-muted me-2" data-rating="2"></i>
                        <i class="fas fa-star fa-2x text-muted me-2" data-rating="3"></i>
                        <i class="fas fa-star fa-2x text-muted me-2" data-rating="4"></i>
                        <i class="fas fa-star fa-2x text-muted me-2" data-rating="5"></i>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="feedback" class="form-label">反馈意见（可选）：</label>
                    <textarea class="form-control" id="feedback" rows="3" placeholder="请告诉我们您的想法..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitRating">提交评价</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        let currentSessionId = '@sessionId';
        let currentUserId = '@userId';
        let currentRating = 0;
        let currentMessageId = '';
        let pendingIntent = null; // 记录机器人正在等待的补充信息类型
        let isSending = false; // 发送节流
        const pendingPayloadByMessageId = new Map(); // 缓存待发送内容，便于失败重试

        $(document).ready(function() {
            // 发送消息
            $('#sendButton').click(sendMessage);
            // 输入框键盘行为：Enter 发送，Shift+Enter 换行
            $('#messageInput').on('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    $('#sendButton').click();
                }
            }).on('input', function(){
                // 自动高度
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 120) + 'px';
            });

            // 建议操作点击即发
            $(document).on('click', '.suggested-action', function(){
                const title = $(this).text().trim();
                $('#messageInput').val(title);
                $('#sendButton').click();
            });

            // 转人工（占位：弹提示）
            $('#handoffBtn').click(function(){
                alert('已为您提交人工客服请求，稍后将有客服接入（演示占位，可接入IM/工单系统）。');
            });

            // 建议区转人工
            $(document).on('click', '#suggestHandoff', function(){
                $('#handoffBtn').click();
            });

            // 首次进入，尝试加载历史
            loadConversationHistory();

            // 快速问题
            $('.quick-question').click(function() {
                const question = $(this).data('question');
                $('#messageInput').val(question);
                sendMessage();
            });

            // 清空对话
            $('#clearChat').click(function() {
                $('#chatMessages').html('');
                addWelcomeMessage();
            });

            // 加载历史
            $('#loadHistory').click(function() {
                loadConversationHistory();
            });

            // 评价功能
            $('.rating-stars i').click(function() {
                const rating = $(this).data('rating');
                currentRating = rating;
                $('.rating-stars i').removeClass('text-warning').addClass('text-muted');
                for (let i = 1; i <= rating; i++) {
                    $(`.rating-stars i[data-rating="${i}"]`).removeClass('text-muted').addClass('text-warning');
                }
            });

            $('#submitRating').click(function() {
                submitRating();
            });
        });

        function sendMessage() {
            if (isSending) return; // 节流
            const raw = $('#messageInput').val().trim();
            if (!raw) return;

            // 意图补全
            const completed = completeIntentIfNeeded(raw);

            // 添加用户消息到界面
            const tempId = 'tmp_' + Date.now();
            addMessage(completed.displayText, true, null, completed.hint);
            $('#messageInput').val('');

            // 显示加载状态
            addLoadingMessage();

            isSending = true;
            $('#sendButton').prop('disabled', true);

            // 发送到API
            $.ajax({
                url: '@Url.Action("SendMessage", "Chat")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    message: completed.sendText,
                    userId: currentUserId,
                    sessionId: currentSessionId
                }),
                success: function(response) {
                    // 移除加载消息
                    $('.loading-message').remove();
                    
                    // 添加AI回复
                    addMessage(response.content, false, response);
                    
                    // 基于机器人回复更新 pendingIntent
                    inferPendingIntent(response.content);

                    // 更新建议操作
                    updateSuggestedActions(response.suggestedActions);
                },
                error: function() {
                    $('.loading-message').remove();
                    addMessage('抱歉，服务暂时不可用，请稍后重试。', false);
                    addRetryBar(tempId, completed);
                },
                complete: function(){
                    isSending = false;
                    $('#sendButton').prop('disabled', false);
                }
            });
        }

        function addMessage(content, isUser, response = null, hint = null) {
            const timestamp = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            const messageId = response ? response.messageId : 'msg_' + Date.now();
            
            let messageHtml = `
                <div class="d-flex mb-3 ${isUser ? 'justify-content-end' : ''}">
                    ${!isUser ? '<div class="flex-shrink-0"><div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;"><i class="fas fa-robot text-white"></i></div></div>' : ''}
                    <div class="flex-grow-1 ${isUser ? 'text-end' : 'ms-3'}">
                        <div class="bg-${isUser ? 'primary text-white' : 'light'} rounded p-3">
                            <p class="mb-0">${content}</p>
                            ${hint ? `<div class='mt-2'><small class='text-warning'><i class='fas fa-wand-magic-sparkles me-1'></i>${hint}</small></div>` : ''}
                            ${response && response.requiresHumanIntervention ? '<div class="mt-2"><span class="badge bg-warning">需要人工干预</span></div>' : ''}
                        </div>
                        <div class="d-flex align-items-center mt-1 ${isUser ? 'justify-content-end' : ''}">
                            <small class="text-muted me-2">${timestamp}</small>
                            ${!isUser ? `<button class="btn btn-sm btn-outline-primary" onclick="showRatingModal('${messageId}')"><i class="fas fa-star me-1"></i>评价</button>` : ''}
                        </div>
                    </div>
                    ${isUser ? '<div class="flex-shrink-0 ms-3"><div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;"><i class="fas fa-user text-white"></i></div></div>' : ''}
                </div>
            `;
            
            $('#chatMessages').append(messageHtml);
            scrollToBottom();
        }

        // 追加：失败重试按钮
        function addRetryBar(messageId, payload){
            pendingPayloadByMessageId.set(messageId, payload);
            const html = `
                <div class="text-end mb-2" id="retry_${messageId}">
                    <small class="text-muted me-2">发送失败</small>
                    <button class="btn btn-sm btn-outline-secondary" onclick="retrySend('${messageId}')">
                        <i class="fas fa-rotate-right me-1"></i>重试
                    </button>
                </div>`;
            $('#chatMessages').append(html);
            scrollToBottom();
        }

        function retrySend(messageId){
            const payload = pendingPayloadByMessageId.get(messageId);
            if(!payload) return;
            $(`#retry_${messageId}`).remove();
            $('#messageInput').val(payload.displayText);
            $('#sendButton').click();
        }

        function addLoadingMessage() {
            const loadingHtml = `
                <div class="d-flex mb-3 loading-message">
                    <div class="flex-shrink-0">
                        <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <i class="fas fa-robot text-white"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="bg-light rounded p-3">
                            <div class="d-flex align-items-center">
                                <div class="spinner-border spinner-border-sm me-2" role="status"></div>
                                <span class="text-muted">AI正在思考中...</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            $('#chatMessages').append(loadingHtml);
            scrollToBottom();
        }

        function addWelcomeMessage() {
            const welcomeHtml = `
                <div class="d-flex mb-3">
                    <div class="flex-shrink-0">
                        <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <i class="fas fa-robot text-white"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="bg-light rounded p-3">
                            <p class="mb-0">您好！我是MES系统智能客服助手，专业为您提供生产管理相关服务。我可以协助您：</p>
                            <ul class="mb-0 mt-2">
                                <li>查询设备运行状态和生产数据</li>
                                <li>创建和管理维护工单</li>
                                <li>调整生产计划和排程</li>
                                <li>解答技术问题和操作指导</li>
                                <li>处理设备报警和异常情况</li>
                            </ul>
                            <p class="mb-0 mt-2">请详细描述您的需求，我将为您提供专业的解决方案。</p>
                        </div>
                        <small class="text-muted">${new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</small>
                    </div>
                </div>
            `;
            $('#chatMessages').append(welcomeHtml);
        }

        function updateSuggestedActions(actions) {
            if (!actions || actions.length === 0) {
                $('#suggestedActions').html('<div class="list-group-item border-0"><small class="text-muted">暂无建议操作</small></div>');
                return;
            }

            let actionsHtml = '';
            actions.forEach(action => {
                actionsHtml += `
                    <button class="list-group-item list-group-item-action border-0 suggested-action" data-action="${action.type}">
                        <i class="fas fa-${getActionIcon(action.type)} text-primary me-2"></i>
                        <strong>${action.title}</strong>
                        <br><small class="text-muted">${action.description}</small>
                    </button>
                `;
            });
            
            $('#suggestedActions').html(actionsHtml || '<div class="list-group-item border-0"><small class="text-muted">暂无建议操作</small></div>');
        }

        function getActionIcon(actionType) {
            const iconMap = {
                'CreateWorkOrder': 'plus',
                'QueryProduction': 'chart-line',
                'AdjustSchedule': 'calendar',
                'ViewManual': 'book',
                'ContactHuman': 'user',
                'Other': 'cog',
                'QueryStatus': 'heartbeat',
                'QueryProductionHistory': 'chart-area',
                'QueryDeviceInfo': 'info-circle',
                'SetTimeRange': 'clock',
                'ApplyPermission': 'key',
                'ViewAlarmHistory': 'exclamation-triangle',
                'ExportReport': 'download'
            };
            return iconMap[actionType] || 'cog';
        }

        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function loadConversationHistory() {
            $.ajax({
                url: '@Url.Action("GetHistory", "Chat")',
                type: 'GET',
                data: { sessionId: currentSessionId, limit: 20 },
                success: function(history) {
                    if (history && history.length > 0) {
                        $('#chatMessages').html('');
                        history.forEach(msg => {
                            addMessage(msg.content, msg.isUser);
                        });
                    }
                },
                complete: function(){
                    // 历史加载后，基于最后一条机器人提示推断 pendingIntent
                    const lastBot = $('#chatMessages .d-flex').not('.justify-content-end').last().text();
                    inferPendingIntent(lastBot);
                }
            });
        }

        function showRatingModal(messageId) {
            currentMessageId = messageId;
            currentRating = 0;
            $('.rating-stars i').removeClass('text-warning').addClass('text-muted');
            $('#feedback').val('');
            $('#ratingModal').modal('show');
        }

        function submitRating() {
            if (currentRating === 0) {
                alert('请选择评分');
                return;
            }

            const feedback = $('#feedback').val();
            
            $.ajax({
                url: '@Url.Action("RateResponse", "Chat")',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    sessionId: currentSessionId,
                    messageId: currentMessageId,
                    rating: currentRating,
                    feedback: feedback
                }),
                success: function(response) {
                    if (response.success) {
                        alert('评价提交成功，感谢您的反馈！');
                        $('#ratingModal').modal('hide');
                    } else {
                        alert('评价提交失败：' + response.message);
                    }
                },
                error: function() {
                    alert('评价提交失败，请稍后重试');
                }
            });
        }

        function inferPendingIntent(botText) {
            if (!botText) { pendingIntent = null; return; }
            // 常见提示语匹配
            const needDevice = /(设备|产线).*(名称|编号|编码)|请提供.*(设备|产线)/;
            const needOrder = /(工单).*(编号|号)/;
            if (needDevice.test(botText)) {
                pendingIntent = 'deviceQuery';
                return;
            }
            if (needOrder.test(botText)) {
                pendingIntent = 'orderQuery';
                return;
            }
            pendingIntent = null;
        }

        function completeIntentIfNeeded(input) {
            const result = { sendText: input, displayText: input, hint: null };

            // 识别看似编码的文本：字母+数字，长度3-10，例如 H0012、A12、LINE-03
            const codeLike = /^([A-Za-z]{1,4}[-_]?)?\d{2,6}$/;
            if (!pendingIntent) {
                // 无待定意图时也可做通用补全：若像编码，则默认按“查询设备产量”
                if (codeLike.test(input)) {
                    result.sendText = `查询设备/产线 ${input} 的当前产量`;
                    result.displayText = `${input}`;
                    result.hint = `已自动补全为“${result.sendText}”`;
                }
                return result;
            }

            if (pendingIntent === 'deviceQuery' && codeLike.test(input)) {
                result.sendText = `查询设备/产线 ${input} 的当前产量`;
                result.displayText = `${input}`;
                result.hint = `已根据上文提示补全：${result.sendText}`;
                pendingIntent = null;
                return result;
            }

            if (pendingIntent === 'orderQuery' && codeLike.test(input)) {
                result.sendText = `查询工单 ${input} 的最新进度`;
                result.displayText = `${input}`;
                result.hint = `已根据上文提示补全：${result.sendText}`;
                pendingIntent = null;
                return result;
            }

            return result;
        }
    </script>
}

<style>
.card {
    transition: transform 0.2s ease-in-out;
}

.card:hover {
    transform: translateY(-2px);
}

.bg-primary {
    background-color: #667eea !important;
}

.btn-primary {
    background-color: #667eea;
    border-color: #667eea;
}

.btn-primary:hover {
    background-color: #5a6fd8;
    border-color: #5a6fd8;
}

.list-group-item-action:hover {
    background-color: #f8f9fa;
    transform: translateX(5px);
    transition: all 0.2s ease-in-out;
}

.rating-stars i {
    cursor: pointer;
    transition: color 0.2s ease-in-out;
}

.rating-stars i:hover {
    color: #ffc107 !important;
}

#chatMessages::-webkit-scrollbar {
    width: 6px;
}

#chatMessages::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

#chatMessages::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

#chatMessages::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style> 